package com.cloud.little.config.mybatisplus;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;

import java.lang.reflect.Field;

/**
 * 熊荣健
 * 分页转成自动的mybatisplus条件包装类
 *
 * @param <T>
 */
public class PageToWrapper<T> {

    //通过反射获取包装类的查询条件
    public Wrapper<T> getWrapper(Object obj) {
        Class<?> aClass = obj.getClass();


        EntityWrapper<T> entityWrapper = new EntityWrapper<>();

        Field[] declaredFields = aClass.getDeclaredFields();

        for (Field declaredField : declaredFields) {
            try {
                String fieldName = declaredField.getName();
                if ("serialVersionUID".equals(fieldName)) continue;

                //避免无法访问私有属性
                declaredField.setAccessible(true);
                Object fieldValue = declaredField.get(obj);
                if (fieldValue != null) {
                    TableId tableId = declaredField.getAnnotation(TableId.class);
                    if (tableId != null) {
                        entityWrapper.eq(tableId.value(), fieldValue);
                    }
                    TableField tableField = declaredField.getAnnotation(TableField.class);
                    if (tableField != null) {
                        entityWrapper.eq(tableField.value(), fieldValue);
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                throw new RuntimeException("PageToWrapper反射获取字段出错:" + e.getMessage());
            }

        }
        return entityWrapper;
    }

}
